package com.imust.springbootproject.web;

import com.imust.springbootproject.po.Traveler;
import com.imust.springbootproject.service.TravelerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
public class TravelerController {
    @Autowired
    private TravelerService travelerService;


    @GetMapping({"/login", "/login.html"})
    public String login(){
        return "login";
    }

    @PostMapping("/login")
    public String loginPost(@RequestParam String travelername,
                            @RequestParam String travelerpassword,
                            RedirectAttributes attributes,
                            HttpSession session){
        Traveler traveler = travelerService.login(travelername, travelerpassword);
        if (traveler == null){
            attributes.addAttribute("message", "用户名或密码错误");
            return "redirect:/login";
        }else{
            session.setAttribute("traveler", traveler);
            return "redirect:/";
        }
    }

    @GetMapping("/register")
    public String register(){
        return "register";
    }

    @PostMapping("/register")
    public String registerPost(Traveler traveler, RedirectAttributes attributes){
        Traveler t = travelerService.findByTravelername(traveler.getTravelername());
        if (t != null){
            attributes.addAttribute("message", "这个用户已经存在");
            return "redirect:/register";
        }
        Traveler traveler1 = travelerService.save(traveler);
        attributes.addAttribute("traveler", traveler1);
        return "redirect:/login";
    }
}
